package com.onemile.app;

import java.util.ArrayList;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

import com.onemile.app.base.BaseUI;
import com.onemile.controls.AdpLV_ShopList;
import com.onemile.data.DXml;
import com.onemile.data.DXml.FieldList;
import com.onemile.entity.PubConst;
import com.onemile.entity.Session;
import com.onemile.entity.model.ELocation;
import com.onemile.entity.model.EShopInfo;
import com.onemile.location.CellInfoManager;
import com.onemile.location.CellLocationManager;
import com.onemile.location.NetGPRSLocation;
import com.onemile.location.WifiInfoManager;
import com.onemile.net.NetClient;
import com.onemile.utils.UtiDialogsFactory;

public class UIShopList extends BaseUI
{
   private String shopType;

   private ListView listView;
   private EditText edtSearchBar;
   private ImageView imgSearchBar;
   private TextView txtSearchFilter;
   private ImageView imgSearchFilter;

   private boolean isSearch = false;

   private String SortType = "2";
   private String SortField = "12";

   private ProgressBar pbLocationBar;
   private TextView txtLocationBar;
   private ImageView imgLocationBar;
   /**
    * 存储已经加载的页码
    */
   private ArrayList<Object> loadedPageList;
   private AdpLV_ShopList adpCommodityList;
   private LayoutInflater mInflater;

   private View footLoadingView;
   private TextView txtNoData;

   private int MaxDateNum;// 设置一个最大的数据条数，超过即不再加载
   private int lastVisibleIndex; // 最后可见条目的索引
   private int nextPageNum = 1;

   public void CleanPageList()
   {
	  nextPageNum = 1;
	  loadedPageList.clear();
   }

   private void InitControls()
   {
	  mInflater = LayoutInflater.from(this);
	  footLoadingView = mInflater.inflate(R.layout.listview_moredata, null);
	  txtNoData = (TextView)mInflater.inflate(R.layout.all_no_data_txt,null);
	  loadedPageList = new ArrayList<Object>();

	  pbLocationBar = (ProgressBar) findViewById(R.id.pb_location);
	  txtLocationBar = (TextView) findViewById(R.id.txt_location);
	  imgLocationBar = (ImageView) findViewById(R.id.img_location);
	  imgLocationBar.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			GetLocation(true, true);
		 }
	  });

	  listView = (ListView) findViewById(R.id.listShops_shoplist);
	  listView.setOnScrollListener(scrollListener);
	  listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
	  {
		 @Override
		 public void onItemClick(AdapterView<?> arg0, View currentView, int position, long arg3)
		 {
			if (listView.getFooterViewsCount() > 0 && position == listView.getAdapter().getCount() - 1)
			{
			   // 屏蔽掉FootView的单击事件
			}
			else
			{ 
			   try
			   {
				  if(Session.getInstance().GetCommodityCount()>0||Session.getInstance().getCommodityList().size()>0)
				  {
					 if(!((EShopInfo)listView.getAdapter().getItem(position)).getShopsId().equals(Session.getInstance().getCommodityList().get(0).getShopsId()))
				     {
						UtiDialogsFactory.getInstance().ShowToastInfoShort(UIShopList.this, getString(R.string.shop_different_commodity));
		                return;
					 }
				  }
				  if (Session.getInstance().GetCommodityCount() == 0 || Session.getInstance().getCommodityList() == null)
				  {
					 Session.getInstance().setCurrentShop((EShopInfo) listView.getAdapter().getItem(position));
				  }
				  
				  String shopId = ((EShopInfo) listView.getAdapter().getItem(position)).getShopsId();
				  Intent intent = new Intent();
				  intent.setClass(UIShopList.this, UICommodityList.class);
				  intent.putExtra(PubConst.Intent_Key.SHOP_ID, shopId);
				  startActivity(intent);
			   }
			   catch (Exception e)
			   {
				  // TODO: handle exception
			   }
			}
		 }
	  });

	  edtSearchBar = (EditText) findViewById(R.id.edtShopName_shoplist_searchbar);

	  imgSearchBar = (ImageView) findViewById(R.id.imgSearch_shoplist_searchbar);
	  imgSearchBar.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			if (edtSearchBar.getText().toString().trim().equals(""))
			{
			   UtiDialogsFactory.getInstance().ShowToastInfoShort(UIShopList.this, getString(R.string.shop_input_a_keyword));
			}
			else
			{
			   isSearch = true;
			   executeAsyncTask(PubConst.TaskName.SEARCH_SHOP_LIST, new Object[] { true });
			}
		 }
	  });

	  imgSearchFilter = (ImageView) findViewById(R.id.imgFilter_shoplist_searchbar);
	  imgSearchFilter.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			final String[] items = { "按照距离", "按照名称", "按照人气" };
			UtiDialogsFactory.getInstance().ShowItemsDialog(UIShopList.this, items, new DialogInterface.OnClickListener()
			{
			   @Override
			   public void onClick(DialogInterface dialog, int which)
			   {
				  txtSearchFilter.setText(items[which]);
				  switch (which)
				  {
					 case 0:// 按照距离显示
						GetLocation(true, false);
						break;
					 case 1:// 按照名称
						SortField = "1";
						executeAsyncTask(PubConst.TaskName.SHOP_LIST_LOCATION, new Object[] { true });
						break;
					 case 2:// 按照人气

						break;
				  }
				  dialog.dismiss();
			   }
			});
		 }
	  });

	  txtSearchFilter = (TextView) findViewById(R.id.txtFilter_shoplist_searchbar);
	  txtSearchFilter.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			final String[] items = { "按照距离", "按照名称", "按照人气" };
			UtiDialogsFactory.getInstance().ShowItemsDialog(UIShopList.this, items, new DialogInterface.OnClickListener()
			{
			   @Override
			   public void onClick(DialogInterface dialog, int which)
			   {
				  txtSearchFilter.setText(items[which]);
				  dialog.dismiss();
			   }
			});
		 }
	  });
   }

   private OnScrollListener scrollListener = new OnScrollListener()
   {
	  @Override
	  public void onScrollStateChanged(AbsListView view, int scrollState)
	  {
	  }

	  @Override
	  public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
	  {
		 try
		 {
			lastVisibleIndex = firstVisibleItem + visibleItemCount - 1;
			if (visibleItemCount != 0)
			{
			   if ((firstVisibleItem + visibleItemCount) == totalItemCount)// 表示已经滚动到底部了
			   {
				  nextPageNum = totalItemCount / PubConst.Setting.GOODSLIST_NUM + 1;// 计算当前是第几页数据

				  if (listView.getFooterViewsCount() < 1)// 当没有其他数据加载时，再加载,确保同一时间只运行一个下载线程
				  {
					 if (!loadedPageList.contains(nextPageNum))// 如果没有加载当前页面
					 {
						if (isSearch)
						{
						   executeAsyncTask(PubConst.TaskName.SEARCH_SHOP_LIST, new Object[] { false });
						}
						else
						{
						   executeAsyncTask(PubConst.TaskName.SHOP_LIST_LOCATION, new Object[] { false });
						}
					 }
				  }
			   }
			}
		 }
		 catch (Exception e)
		 {
			Log.e(PubConst.Tag.ERROR, "UIShopList_onScroll()", e);
		 }
	  }
   };

   private void GetLocation(final boolean IsCleanResult, boolean IsLocationAgain)
   {
	  // 如果坐标为空，则重新定位，否则直接取坐标
	  SharedPreferences sp = getSharedPreferences(PubConst.Setting.Setting, Activity.MODE_PRIVATE);
	  if (IsLocationAgain)
	  {
		 Editor editor = sp.edit();
		 editor.remove(PubConst.Setting.Latitude);
		 editor.remove(PubConst.Setting.Longitude);
		 editor.remove(PubConst.Setting.Address);
		 editor.commit();
	  }

	  if (sp.getString(PubConst.Setting.Latitude, "").equals(""))
	  {
		 UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UIShopList.this, getString(R.string.shop_be_locationing));
		 NetGPRSLocation location = new NetGPRSLocation(UIShopList.this, new NetGPRSLocation.TaskCallBack()
		 {
			@Override
			public void DoWhenComplete(ELocation result)
			{
			   if (result != null)
			   {
				  SharedPreferences.Editor editor = getSharedPreferences(PubConst.Setting.Setting, Activity.MODE_PRIVATE).edit();
				  editor.putString(PubConst.Setting.Latitude, String.valueOf(result.getLatitude()));
				  editor.putString(PubConst.Setting.Longitude, String.valueOf(result.getLongitude()));
				  editor.putString(PubConst.Setting.Address, String.valueOf(result.getAddress()));
				  editor.commit();
				  txtLocationBar.setText(result.getAddress());

				  UtiDialogsFactory.getInstance().DismissLoadingDialog();

				  Session.getInstance().setLatitude(Double.valueOf(result.getLatitude()));
				  Session.getInstance().setLongitude(Double.valueOf(result.getLongitude()));
				  Session.getInstance().setAddress(result.getAddress());

				  executeAsyncTask(PubConst.TaskName.SHOP_LIST_LOCATION, new Object[] { IsCleanResult });
			   }
			}
		 });
		 location.execute((Void) null);

		 // UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UIShopList.this,
		 // getString(R.string.shop_be_locationing));
		 // CellInfoManager cellManager = new CellInfoManager(UIShopList.this);
		 // WifiInfoManager wifiManager = new WifiInfoManager(UIShopList.this);
		 // CellLocationManager locationManager = new
		 // CellLocationManager(UIShopList.this, cellManager, wifiManager)
		 // {
		 // @Override
		 // public void onLocationChanged()
		 // {
		 // SharedPreferences.Editor
		 // editor=getSharedPreferences(PubConst.Setting.Setting,
		 // Activity.MODE_PRIVATE).edit();
		 // editor.putString(PubConst.Setting.Latitude,
		 // String.valueOf(this.latitude()));
		 // editor.putString(PubConst.Setting.Longitude,
		 // String.valueOf(this.longitude()));
		 // editor.putString(PubConst.Setting.Address,
		 // String.valueOf(this.address()));
		 // editor.commit();
		 // txtLocationBar.setText(this.address());
		 //
		 // UtiDialogsFactory.getInstance().DismissLoadingDialog();
		 //
		 // Session.getInstance().setLatitude(this.latitude());
		 // Session.getInstance().setLongitude(this.longitude());
		 // Session.getInstance().setAddress(this.address());
		 // this.stop();
		 //
		 // executeAsyncTask(PubConst.TaskName.SHOP_LIST_LOCATION,new Object[]{
		 // IsCleanResult });
		 // }
		 // };
		 // locationManager.start();
	  }
	  else
	  {
		 Session.getInstance().setLatitude(Double.valueOf(sp.getString(PubConst.Setting.Latitude, "")));
		 Session.getInstance().setLongitude(Double.valueOf(sp.getString(PubConst.Setting.Longitude, "")));
		 Session.getInstance().setAddress(sp.getString(PubConst.Setting.Address, ""));
		 txtLocationBar.setText(Session.getInstance().getAddress());
		 executeAsyncTask(PubConst.TaskName.SHOP_LIST_LOCATION, new Object[] { IsCleanResult });
	  }

   }

   @Override
   protected void onCreateOverride(Bundle savedInstanceState)
   {
	  InitControls();
	  GetLocation(false, false);
   }

   @Override
   public int SetContentViewLayoutResId()
   {
	  return R.layout.shoplist;
   }

   @Override
   public void SetTopToolbar(TextView topTxt, ImageView leftImBtn, ImageView rightImgBtn, RelativeLayout rightRay, TextView cartNum)
   {
	  topTxt.setText(getString(R.string.title_shoplist));
	  shopType = String.valueOf(getIntent().getIntExtra(PubConst.Intent_Key.SHOP_TYPE, 0));
	  rightRay.setVisibility(View.VISIBLE);
	  SetRightBtnToCart();
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  if (taskName.equals(PubConst.TaskName.SHOP_LIST) || taskName.equals(PubConst.TaskName.SEARCH_SHOP_LIST) || taskName.equals(PubConst.TaskName.SHOP_LIST_LOCATION))
	  {
		 listView.addFooterView(footLoadingView);
		 txtNoData.setVisibility(View.GONE);
		 if ((Boolean) params[0])
		  {
			adpCommodityList = null;
			listView.setAdapter(null);
			CleanPageList();// 清除已经保存的“已加载页面列表”
		 }
		 if (listView.getChildCount() < 1)// 当列表不存在的时候才显示第一次加载的画面
		 {
			UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UIShopList.this, getString(R.string.dialog_loading));
			  adpCommodityList = new AdpLV_ShopList(UIShopList.this);
			  listView.setAdapter(adpCommodityList);
			listView.removeFooterView(footLoadingView);
		 }
	  }
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params)
   {
	  try
	  {
		 if (taskName != null && taskName.equals(PubConst.TaskName.SHOP_LIST_LOCATION))
		 {
			return NetClient.GetShopListByType_S(shopType, SortType, SortField, nextPageNum, 10, Session.getInstance().getLatitude(), Session.getInstance().getLongitude());
		 }
		 if (taskName != null && taskName.equals(PubConst.TaskName.SEARCH_SHOP_LIST))
		 {
			return NetClient.SearchShopListByName_S(edtSearchBar.getText().toString().trim(), shopType, SortType, SortField, nextPageNum, 10, Session.getInstance().getLatitude(), Session
				  .getInstance().getLongitude());
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UIShopList_onAsyncTaskInBackground(taskName, params) ", e);
		 }
	  }
	  return null;

   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  try
	  {
		 if (taskName.equals(PubConst.TaskName.SHOP_LIST) || taskName.equals(PubConst.TaskName.SEARCH_SHOP_LIST))
		 {
			if (result != null)// 有结果
			{
			   DXml data = (DXml) result;

			   ArrayList<EShopInfo> list = new ArrayList<EShopInfo>();
			   EShopInfo shopInfo = null;
			   int size = data.getBody().getChilds().length;
			   for (int i = 0; i < size; i++)
			   {
				  FieldList fieldList = data.getBody().GetFieldList(i);

				  shopInfo = new EShopInfo();
				  shopInfo.setShopsId(fieldList.GetFieldValue("ShopsId"));
				  shopInfo.setShopsName(fieldList.GetFieldValue("ShopsName"));
				  shopInfo.setShopsType(fieldList.GetFieldValue("ShopsType"));
				  shopInfo.setShopsPraise(fieldList.GetFieldValue("ShopsPraise"));
				  shopInfo.setShopsPoor(fieldList.GetFieldValue("ShopsPoor"));
				  shopInfo.setConsumption(fieldList.GetFieldValue("Consumption"));
				  shopInfo.setRecommendedDishes(fieldList.GetFieldValue("RecommendedDishes"));
				  shopInfo.setDeliveryDistance(fieldList.GetFieldValue("DeliveryDistance"));
				  shopInfo.setLowestPrice(fieldList.GetFieldValue("LowestPrice"));
				  shopInfo.setFreight(fieldList.GetFieldValue("Freight"));
				  shopInfo.setDistance(fieldList.GetFieldValue("Distance"));
				  shopInfo.setOpeningTime(fieldList.GetFieldValue("OpeningTime"));
				  shopInfo.setClosingTime(fieldList.GetFieldValue("ClosingTime"));
				  shopInfo.setCouponNum(fieldList.GetFieldInt32("CouponNum"));
				  list.add(shopInfo);
			   }

			   adpCommodityList.addItem(list);
			   adpCommodityList.notifyDataSetChanged();
			   loadedPageList.add(nextPageNum);
			}
			else
			// 如果没有找到结果又是第一次加载数据。显示 无数据
			{
			   if (listView.getChildCount() < 1 || (listView.getChildCount() == 1 && listView.getFooterViewsCount() == 1))
			   {
				  txtNoData.setVisibility(View.VISIBLE);
			   }
			}
			
		
			// 第一次打开时显示
			if (listView.getChildCount() < 1 || (listView.getChildCount() == 1 && listView.getFooterViewsCount() == 1))
			{
			   UtiDialogsFactory.getInstance().DismissLoadingDialog();
			}
			if (listView.getFooterViewsCount() > 0)
			{
			   listView.removeFooterView(footLoadingView);
			}
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UIShopList_onAsyncTaskEnd(taskId, taskName, params, result) ", e);
		 }
	  }
   }

   @Override
   public boolean onKeyDown(int keyCode, KeyEvent event)
   {
	  // if(keyCode==event.KEYCODE_BACK)
	  // {
	  //
	  // }
	  return super.onKeyDown(keyCode, event);
   }
}
